package com.cbh.amadeus.client.handler;

import com.cbh.amadeus.client.receiver.component.SubscriberComponent;
import com.cbh.amadeus.client.receiver.tool.MessageRepositoryModelTool;
import com.cbh.amadeus.common.enums.MessageType;
import com.cbh.amadeus.common.protocol.AmadeusMessage;
import com.cbh.amadeus.common.protocol.AmadeusMessageWrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ChenBiHui
 * @date 2025/5/23
 */
@Slf4j
public class RejectHandler extends SimpleChannelInboundHandler<AmadeusMessageWrap> {

    private final SubscriberComponent component;

    public RejectHandler(SubscriberComponent component) {
        this.component = component;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AmadeusMessageWrap msg) {
        MessageType type = MessageType.find(msg.getType());
        if (type == MessageType.REJECT) {
            AmadeusMessage message = msg.getMessage();
            MessageRepositoryModelTool tool = component.getMessageRepositoryModelTool();
            tool.reject(message.getTopic(), message.getMessageId());
            log.info(
                    "===== [REJECT] Topic [{}], message-id [{}] has reject =====",
                    message.getTopic(),
                    message.getMessageId()
            );
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
